package com.framework.yhbapi.controller;

import com.framework.service.yhbservice.YhbCurrentCountService;
import com.framework.service.yhbservice.YhbUserOrderService;
import com.framework.utils.ali.AliPay;
import com.framework.yhbEntity.currentcount.YhbCurrentCount;
import com.framework.yhbEntity.user.YhbUserOrder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 功能描述: 回调
 *
 * @author ck
 * @date 2018/9/27 10:48
 */
@RestController
@Api(value="回调模块",tags={"回调模块"})
@RequestMapping("yhbPayBack")
public class PayCallbackController {


	@Autowired
	private YhbCurrentCountService yhbCurrentCountService;

	@Autowired
	private YhbUserOrderService yhbUserOrderService;
	/**
	 * 连连代付回调
	 * @param req
	 * @return
	 *//*
	@PostMapping("notValidate/lianlianPayCallback")
	@ApiOperation("连连支付回调")
	public Map<String,Object> lianlianPayCallback(HttpServletRequest req) {
		Map<String,Object> map = payCallbackService.lianlianResultNotification(req);
		return map;
	}*/

	/**
	 * 支付宝订单回调
	 * @param requests
	 * @return
	 */
	@PostMapping(value = "notValidate/aliPaycallBack")
	@ApiOperation("支付回调")
	public String aliPaycallBack(HttpServletRequest requests){
		//1.从支付宝回调的request域中取值
		Map<String, String[]> requestParams = requests.getParameterMap();
		Map<String, String> params = new HashMap<>();
		System.out.println("从支付宝回调的request域中取值:requestParams===================================" + requestParams);
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = iter.next();
			String[] values = requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
			params.put(name, valueStr);
		}
		// 2.封装必须参数
		String outTradeNo = requests.getParameter("out_trade_no"); // 商户订单号
		System.err.println("out_trade_no==================================" + outTradeNo);
		String orderType = requests.getParameter("body"); // 订单内容
		System.out.println("orderType==================================" + orderType);
		String tradeStatus = requests.getParameter("trade_status"); // 交易状态
		System.err.println("tradeStatus=================================" + tradeStatus);
		// 3.签名验证(对支付宝返回的数据验证，确定是支付宝返回的)
		//boolean signVerified = false;
		//查询订单信息
		YhbUserOrder orders = yhbUserOrderService.queryOrderByOrderNo(outTradeNo);
		//签名通过
		//if(signVerified){
			//成功订单
			if(!StringUtils.equals(tradeStatus,"WAIT_BUYER_PAY")){
				if(StringUtils.equals(tradeStatus,"TRADE_SUCCESS") || StringUtils.equals(tradeStatus,"TRADE_FINISHED")){
					//修改订单状态

					yhbUserOrderService.successPayState(orders.getOrderNo(),AliPay.ALI_PAY_TYPE);
					//添加账户流水日志
					YhbCurrentCount account=new YhbCurrentCount();
					account.setIncome(2);
					account.setIncomeType(1);
					account.setCreateDate(new Date());
					account.setRelationId(String.valueOf(orders.getYhbOrderId()));
					account.setAmount(orders.getGoodsPrice());
					account.setIsActivity(0);
					yhbCurrentCountService.insert(account);

				}if(StringUtils.equals(tradeStatus,"TRADE_CLOSED")){
					return "success";
				}
			}else{
				return "error";
			}
		//}
		// 只处理支付成功的订单:修改交易表状态,支付成功
		return "success";
	}



}
